import React from 'react'
import Component, { mapStateToProps, mapDispatchToProps } from '@components/Component'
import { connect } from 'react-redux'
import { Button, message, Radio, Modal, Table } from 'antd'
import { ExclamationCircleOutlined, DownloadOutlined } from '@ant-design/icons'
import { addWindow } from '@redux/actions'
import style from '@pages/filingCaseManage/CaseManage.module.less'
import { json2Excel } from '@js/excel'
import CaseNoRender from '@components/CaseNoRender'
import SearchForm from '@components/SearchForm/Index'
import Year from './components/Year'
import UserTag from './components/UserTag'
import { formatDate } from '@src/assets/js/tool'
import nStyle from './normal.module.less'
import EditNote from '@components/CaseNote/EditModal'
const { confirm } = Modal

const extendParams = [
  { name: 'anotheryear_claim', label: '反请求/变更跨年', component: Year, defaultVisible: true },
  { name: 'user_tag', label: '案件标签', component: UserTag, defaultVisible: true }
]

function formatCaseTimeByStatus (l) {
  switch (l.status) {
    case '视为撤回仲裁申请':
    case '已结案':
      return formatDate(l.closure_datetime)
    case '已结案送达':
      return formatDate(l.closure_deliver_datetime)
    case '立案':
      return formatDate(l.docket_datetime)
    case '交费':
      return formatDate(l.fee_pay_datetime)
    case '移交办案':
      return formatDate(l.to_process_datetime)
    case '送达完成':
      return formatDate(l.arrive_datetime)
    case '不予受理':
      return formatDate(l.accept_datetime)
    case '已组庭':
      return formatDate(l.arbitrator_assigntime)
    case '已归档':
      return formatDate(l.file_datetime)
  }
}

// 处理搜索表单扩展字段
function extendCondition (condition, formData) {
  const n = formData.anotheryear_claim
  if (n) {
    condition.push({ k: 'anotheryear_claim', o: 'like', v: `%${n}%` })
  }
  if (formData.user_tag) {
    condition.push({ k: 'user_tag', o: 'like', v: `%${formData.user_tag}%` })
  }
  return { condition, formData }
}

// 获取表格字段配置
function getColumns (refreshFn) {
  const list = [
    {
      title: '序号',
      dataIndex: 'key',
      key: 'index',
      align: 'center',
      width: 60
    },
    {
      title: '案号',
      dataIndex: 'caseno_desc',
      key: 'caseno_desc',
      width: 100,
      render: (v, l) => {
        return <CaseNoRender data={l} note refreshFn={refreshFn} />
      }
    },
    {
      title: '申请人',
      dataIndex: 'applicants',
      key: 'applicants',
      width: 150,
      render: v => {
        return (v || []).filter(li => li.status).map(li => li.name).join('、')
      }
    },
    {
      title: '被申请人',
      dataIndex: 'respondents',
      key: 'respondents',
      width: 150,
      render: v => {
        return (v || []).filter(li => li.status).map(li => li.name).join('、')
      }
    },
    {
      title: '案由',
      dataIndex: 'cause_action',
      key: 'cause_action',
      width: 100
    },
    {
      title: '争议金额',
      dataIndex: 'dispute_amount',
      key: 'dispute_amount',
      width: 120,
      render: v => {
        return String(v || 0).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
      }
    },
    {
      title: '仲裁费',
      dataIndex: 'fee',
      width: 120,
      key: 'fee',
      render: v => {
        return String(v || 0).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
      }
    },
    {
      title: '案件状态',
      dataIndex: 'status',
      key: 'status',
      width: 88
    },
    {
      title: '办案秘书',
      dataIndex: 'processer',
      key: 'processer',
      width: 88
    },
    {
      title: '案件状态操作时间',
      dataIndex: 'docket_datetime',
      key: 'docket_datetime',
      width: 150,
      render: (v, l) => {
        return formatCaseTimeByStatus(l)
      }
    },
    {
      title: '操作',
      dataIndex: 'index',
      key: 'operate',
      width: 100,
      render: (value, line) => {
        if (line.cause_action) {
          return (
            <span className={style['operate-cell']}>
              <span className={style['operate-btn']} onClick={() => this.openDetail(line)}>详情</span>
              <a className={nStyle['opearte-btn']} onClick={() => this.setState({ visible: true, modifyData: line })}>添加便签</a>
            </span>
          )
        }
        return (
          <span className={style['operate-cell']}>
            <span onClick={() => this.openDetail(line)}>详情</span>
            <a className={nStyle['opearte-btn']} onClick={() => this.setState({ visible: true, modifyData: line })}>添加便签</a>
            {/* <span onClick={() => this.fullInfo(line)}>完善信息</span> */}
          </span>
        )
      }
    }
  ]
  return list
}

class AllCaseManage extends Component {
  state = {
    searchToggleBtn: false,
    loading: false,
    list: [],
    status: '全部',
    dictionaries: {}, // 枚举字典
    totalMoney: 0,
    totalCounterMoney: 0,
    totalCounter: 0,
    treeData: [],
    condition: [],
    visible: false,
    modifyData: null,
    pagination: {
      current: 1,
      pageSize: 10,
      total: 0,
      showSizeChanger: true,
      showQuickJumper: true,
      showTotal: total => `共 ${total} 条记录`,
      size: 'small'
    }
  }

  formRef = React.createRef()

  // 完善信息
  fullInfo (data) {
    this.props.addWindow({ id: `AcceptCase-${data.id}`, title: `完善信息-${data.accept_no || data.serial_no}`, componentName: 'AcceptCase', forceRefresh: true, meta: { id: data.id } })
  }

  // 查看案件详情
  openDetail (data) {
    this.props.addWindow({ id: `CaseDetail-${data.id}`, title: `案件详情-${data.caseno_desc || data.acceptno_desc || data.case_no || data.accept_no || data.serial_no}`, componentName: 'CaseDetail', forceRefresh: true, meta: { id: data.id } })
  }

  // 获取案件状态
  getStatus (condition) {
    const { status } = this.state
    const { employeeid } = this.props.userInfo
    condition.push({ k: 'processerid', o: '=', v: employeeid })
    if (status === '在办') {
      condition.push({ k: 'status', o: 'in', v: '移交办案,送达完成,已组庭,已结案' })
    } else if (status === '已归档') {
      condition.push({ k: 'status', o: 'in', v: '已归档' })
    } else if (status !== '全部') {
      condition.push({ k: 'status', o: 'in', v: status })
    } else if (status === '全部') {
      condition.push({ k: 'status', o: 'in', v: '移交办案,送达完成,已组庭,已结案,已结案送达,已归档' })
    }
  }

  // 改变案件状态
  changeStatus (status) {
    this.setState({
      status,
      pagination: {
        ...this.state.pagination,
        current: 1
      }
    }, () => {
      this.getTableData()
    })
  }

  // 获取案件数据
  getTableData () {
    let { pagination, condition } = this.state
    const { current, pageSize } = pagination
    condition = [...condition]
    this.getStatus(condition)
    this.setState({ loading: true })
    this.$get('/api/xapc/case', {
      current,
      page_size: pageSize,
      condition: JSON.stringify(condition)
    }).then(res => {
      this.setState({ loading: false })
      if (res.status === 1) {
        this.setState({
          list: res.data.list.map((li, i) => {
            li.key = pageSize * (current - 1) + i + 1
            return li
          }),
          totalMoney: res.data.sum_dispute_amount,
          totalCounterMoney: res.data.sum_counter_dispute_amount,
          totalCounter: res.data.total_counter,
          pagination: {
            ...pagination,
            total: res.data.total
          }
        })
      } else {
        return message.warning(res.message)
      }
    }).catch(() => this.setState({ loading: false }))
  }

  // 表格请求变化
  tableChange ({ current, pageSize }) {
    this.setState({
      pagination: {
        ...this.state.pagination,
        current,
        pageSize
      }
    }, () => {
      this.getTableData()
    })
  }

  initFormByMeta () {
    const c = this.formRef.current
    const { formData = {} } = this.props.meta || {}
    const keys = Object.keys(formData)
    if ((formData.casetype || [])[0] === '一般案件') {
      formData.casetype = ['其他案件']
    }
    if (keys.length > 0) {
      c.showAll()
    }
    setTimeout(() => {
      c.setFieldsValue(formData)
      c.submit()
    }, 0)
  }

  // 格式化枚举字典
  formatDictionaries (dictionaries = []) {
    const result = {}
    dictionaries.forEach(d => {
      result[d.type] = d.list
    })
    return result
  }

  // 格式化金钱
  formatMoney (money) {
    if (money) {
      return String(money).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
    }
    return money
  }

  // 获取当事人字符串
  getPersonString (list) {
    const res = []
    list.forEach(li => {
      const arr = [li.name]
      try {
        const o = JSON.parse(li.tag)
        arr.push(` - ${o.subject_type_tag}`)
      } catch (e) {}
      if (!li.status) {
        arr.push('（终结）')
      }
      res.push(arr.join(''))
    })
    return res.join('、')
  }

  // 获取当前查询条件的全部数据，并下载excel
  downloadExcel () {
    const current = 1
    const pageSize = 1000000
    const hide = message.loading('导出中', 300)
    const condition = [...this.state.condition]
    this.getStatus(condition)
    this.$get('/api/xapc/case', {
      current,
      page_size: pageSize,
      condition: JSON.stringify(condition)
    }).then(res => {
      hide()
      if (res.status === 1) {
        const list = res.data.list.map((l, i) => {
          const caseno = l.caseno_desc || l.case_no || l.acceptno_desc || l.acceptno
          return {
            序号: pageSize * (current - 1) + i + 1,
            案号: caseno + (l.delay_day ? '(缓)' : ''),
            申请人: this.getPersonString(l.applicants || []),
            被申请人: this.getPersonString(l.respondents || []),
            案由: l.cause_action,
            争议金额: l.dispute_amount || 0,
            仲裁费: l.fee || 0,
            案件状态: l.status,
            办案秘书: l.processer,
            立案时间: formatDate(l.docket_datetime),
            组庭时间: formatDate(l.arbitrator_assigntime),
            结案时间: formatDate(l.closure_datetime),
            归档时间: formatDate(l.file_datetime),
            案件区域分类: l.party_area_tag,
            申请人所在地: l.applicant_area,
            被申请人所在地: l.respondent_area,
            仲裁程序: l.procedure,
            仲裁庭组成: l.arbitrators,
            结案方式: l.closure_type,
            案件标签: l.user_tag,
            审限至: formatDate(l.caseTrialLimit)
          }
        })
        json2Excel([{ data: list, sheetname: '我的案件' }], `${this.props.userInfo.realname}案件列表`)
      } else {
        return message.warning(res.message)
      }
    }).catch(() => hide())
  }

  // 二次弹框确认下载excel
  confirmDownload () {
    confirm({
      icon: <ExclamationCircleOutlined />,
      content: '您确定要导出excel吗？',
      onOk: () => {
        this.downloadExcel()
      }
    })
  }

  // 将文本转化为数字类型
  transformNumber (v) {
    if (v) {
      return Number(v)
    }
  }

  // 改变搜索条件
  changeCondition (d) {
    this.setState({
      condition: d,
      pagination: {
        ...this.state.pagination, current: 1
      }
    }, () => this.getTableData())
  }

  componentDidUpdate (prev) {
    if (prev.meta !== this.props.meta) {
      this.initFormByMeta()
    }
  }

  componentDidMount () {
    this.initFormByMeta()
  }

  render () {
    const columns = getColumns.call(this, () => this.getTableData())
    const { modifyData: m } = this.state
    return (
      <div className={style.container}>
        <EditNote visible={this.state.visible} caseid={m ? m.id : ''} caseno={m ? m.caseno_desc : ''} hide={() => this.setState({ visible: false })} data={this.state.modifyData} refreshFn={() => { this.setState({ visible: false, modifyData: null }); this.getTableData() }} />
        <div className={style['title-line']}>
          <span>{this.props.title}</span>
        </div>
        <SearchForm ref={this.formRef} extendParams={extendParams} extendCondition={(c, f) => extendCondition(c, f)} onChange={d => this.changeCondition(d)} />
        <div className={style['download-btn-line']}>
          <Button type='primary' ghost onClick={() => this.confirmDownload()} icon={<DownloadOutlined />}>导出excel</Button>
          <Radio.Group value={this.state.status} onChange={v => this.changeStatus(v.target.value)}>
            <Radio.Button value='全部'>全部</Radio.Button>
            <Radio.Button value='在办'>在办</Radio.Button>
            <Radio.Button value='移交办案'>移交办案</Radio.Button>
            <Radio.Button value='送达完成'>送达完成</Radio.Button>
            <Radio.Button value='已组庭'>已组庭</Radio.Button>
            <Radio.Button value='已结案'>已结案</Radio.Button>
            <Radio.Button value='已结案送达'>已结案送达</Radio.Button>
            <Radio.Button value='已归档'>已归档</Radio.Button>
          </Radio.Group>
        </div>
        <div className={style['table-btns-line']}>
          <span className={style['table-total']}>
            <span>总案件数 {this.state.pagination.total} 件 / 标的 {this.formatMoney(this.state.totalMoney) || 0} 元 / 反请求案件数： {this.state.totalCounter} 件 / 反请求标的：{this.formatMoney(this.state.totalCounterMoney)} 元</span>
          </span>
        </div>
        <div className={style['table-container']}>
          <Table loading={this.state.loading} columns={columns} dataSource={this.state.list} pagination={this.state.pagination} onChange={v => this.tableChange(v)} />
        </div>
      </div>
    )
  }
}

const mapState = mapStateToProps(function (state) {
  return {
    userInfo: state.basic.userInfo
  }
})

const mapDispatch = mapDispatchToProps(function (dispatch) {
  return {
    addWindow: (i) => dispatch(addWindow(i))
  }
})

export default connect(mapState, mapDispatch)(AllCaseManage)
